package com.zhao.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zhao.entity.User;

public class LoginFilter implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		String url = request.getRequestURI();
		//过滤访问请求并验证登录状态
		if (  url.endsWith(".css")
				|| url.endsWith(".js")
				|| url.endsWith(".jpg")
				|| url.endsWith(".png")
				|| url.endsWith(".jpeg")
				|| url.contains("userLogin.action")
				|| url.contains("goLogin.action")
				|| url.contains("changePasswordSuccess.action")) {
			filterChain.doFilter(request, response);
		} else {
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute("user");
			if (user != null) {
				filterChain.doFilter(request, response);
			}else {
				
				response.sendRedirect(request.getContextPath()+"/user/userAction!goLogin.action");
				//request.getRequestDispatcher("/view/index.jsp").forward(request, response);
			}
		}
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}